package org.rency.common.utils.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 命令行工具类
 * @author: user_rcy@163.com
 * <p>Created on 2015年11月4日</p>
 * @version: V1.0.0
 * @since JDK 1.8
 */
public class CommandUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(CommandUtils.class);

	public static ProcessResponse exec(String cmd) throws Exception{
		logger.info("执行命令:{}.",cmd);
		ProcessResponse resp = new ProcessResponse();
		StringBuilder result = new StringBuilder();
		BufferedReader br = null;
		try {
			String[] execCmd = new String[3];
			if(SystemUtils.IS_OS_WINDOWS){
				execCmd[0] = "cmd.exe";  
				execCmd[1] = "/C";
			}else{
				execCmd[0] = "command.com";  
				execCmd[1] = "/C";
			}
			execCmd[2] = cmd;
			ProcessBuilder pb = new ProcessBuilder(execCmd);
			pb.redirectErrorStream(true);
			Process p = pb.start();
			br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
			int exitValue = p.waitFor();
			if(exitValue == 0 || exitValue == 2){
				resp.setSuccess(true);
			}
			p.destroy();
			String line = null;
			while( (line = br.readLine()) != null){
				result.append(line);
				result.append("\r\n");
			}
			resp.setResult(result);
		} catch (IOException e) {
			logger.error("执行命令[{}]异常.",cmd,e);
			throw e;
		} catch (InterruptedException e) {
			logger.error("执行命令[{}]异常.",cmd,e);
			throw e;
		}finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
		logger.info("执行命令完成, 命令:[{}], 执行结果:[{}].",cmd,resp.toString());
		return resp;
	}
		
	public static class ProcessResponse {
		private boolean isSuccess = false;
		private StringBuilder result;
		
		public ProcessResponse(){}
		
		public void success(StringBuilder result){
			this.isSuccess = true;
			this.result = result;
		}
		
		public boolean isSuccess() {
			return isSuccess;
		}
		public void setSuccess(boolean isSuccess) {
			this.isSuccess = isSuccess;
		}
		public StringBuilder getResult() {
			return result;
		}
		public void setResult(StringBuilder result) {
			this.result = result;
		}
		public String toString(){
			return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
		}
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(exec("javac").toString());
	}
	
}